import { call, put, takeEvery } from 'redux-saga/effects';
import * as actionTypes from '@src/model/actionType';
import * as API from '@src/api/index';
import { get as _get } from 'lodash';

function* fetchLatestBlock(action) {
  const params = _get(action, ['params'], {});
  try {
    const data = yield call(API.getLatestBlock, params);
    yield put({
      type: actionTypes.latestBlock,
      payload: {
        BlockHash: _get(data, ['Data', 'BlockHash'], ''),
        PreBlockHash: _get(data, ['Data', 'PreBlockHash'], ''),
        Timestamp: _get(data, ['Data', 'Timestamp'], 0),
        BlockHeight: _get(data, ['Data', 'BlockHeight'], 0),
        TxCount: _get(data, ['Data', 'TxCount'], 0),
        ProposalNodeId: _get(data, ['Data', 'ProposalNodeId'], ''),
      },
    });
  } catch (err) {
    console.error(err);
  }
}

const sagas = [takeEvery(actionTypes.fetchLatestBlock, fetchLatestBlock)];

export default sagas;
